package landyer.study.charsetdetect;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

/**
 * Created by PC0801 on 2014/8/19.
 */
public class MainCopy {
    public static void main(String[] args) throws IOException {
        test2();
    }

    private static void test2() throws IOException {
        CharsetDetector charDect = new CharsetDetector();

//        File root = new File("E:\\workspace\\YBServer\\src");
//        File root = new File("E:\\workspace\\YBServer\\src\\com\\cs\\ScoreCall.java");
        String srcPath = "E:\\workspace\\DouDiZhuCMCC\\src";
        File root = new File(srcPath);
        String destPath = "E:\\workspace\\DouDiZhuCMCCUTF8\\src";
        Queue<File> queue = new ArrayDeque<File>();
        queue.add(root);
        while (!queue.isEmpty()) {
            File poll = queue.poll();
            if (poll.isDirectory()) {
                for (File tmp : poll.listFiles()) {
                    queue.add(tmp);
                }
            } else {
//                String[] probableSet = charDect.detectChineseCharset(new FileInputStream(poll));
                Charset charset = charDect.detectOneCharset(new FileInputStream(poll));
                String replace = poll.getAbsolutePath().replace(srcPath, destPath);
                File destFile = new File(replace);
                if ("GB2312".equalsIgnoreCase(charset.name())) {
                    String context = FileUtils.readFileToString(poll, charset);
                    FileUtils.writeStringToFile(destFile, context, Charsets.UTF_8, false);
                    System.out.println("gbk to utf8 : " + destFile.getAbsolutePath());
                } else {
                    boolean isBom = charDect.isBom(new FileInputStream(poll));
                    if (isBom) {
//                        System.out.println(charset.name() + "\t\t\tbom:" + isBom + "\t" + poll.getAbsolutePath());
//                    charDect.removeBom(poll);
                        byte[] data = FileUtils.readFileToByteArray(poll);
                        FileUtils.writeByteArrayToFile(destFile, Arrays.copyOfRange(data,3,data.length));
                        System.out.println("remove bom : "+destFile.getAbsolutePath());
                    }else{
                        FileUtils.copyFile(poll,destFile);
                        System.out.println("copy to : "+destFile.getAbsolutePath());
                    }
                }

            }
        }
    }
}
